package com.example.xuecheng.contentservice.service.impl;

import com.example.xuecheng.contentservice.mapper.CourseCategoryMapper;
import com.example.xuecheng.contentservice.service.CourseCategoryService;
import dto.CourseCategoryTreeDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {
    @Autowired
    private CourseCategoryMapper courseCategoryMapper;
    @Override
    public List<CourseCategoryTreeDto> getCourseCategoryTreeNodes() {
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes();
        String parentPath="1";
        //将list转map 以备使用
        Map<String, CourseCategoryTreeDto> mapTemp= courseCategoryTreeDtos
                .stream().filter(item -> !parentPath.equals(item.getPath()))
                .collect(Collectors.toMap(key -> key.getPath(), value -> value, (key1, key2) -> key2));
        //结果list
        ArrayList<CourseCategoryTreeDto> categoryTreeDtos= new ArrayList<>();
        courseCategoryTreeDtos.stream()
                .filter(item->!parentPath.equals(item.getPath()))
                        .forEach(item->{
                    if(item.getParentPath().equals(parentPath)){
                        categoryTreeDtos.add(item);
                    }
                    CourseCategoryTreeDto categoryTreeDto = mapTemp.get(item.getParentPath());
                    if(categoryTreeDto!=null){
                        if(categoryTreeDto.getChildrenTreeNodes()==null){
                            categoryTreeDto.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                        }
                        categoryTreeDto.getChildrenTreeNodes().add(item);
                    }
                });
        return  categoryTreeDtos;
    }
}
